package com.joyd.joydlib.dev

import android.accessibilityservice.AccessibilityService
import android.app.Instrumentation
import android.content.Context
import android.graphics.Path
import android.graphics.Point
import android.os.Build
import android.os.Handler
import android.os.Looper
import android.util.Log
import android.view.Display
import android.view.InputDevice
import android.view.InputEvent
import android.view.MotionEvent
import android.view.ViewConfiguration
import android.view.WindowManager
import androidx.annotation.RequiresApi
import com.joyd.joydlib.dev.AccessibilityServiceHelper
import java.lang.reflect.*
import java.lang.reflect.InvocationHandler
import java.lang.reflect.Proxy

/**
 * 屏幕点击工具类
 * 提供点击屏幕指定位置的功能
 */
object ScreenTapHelper {
    private const val TAG = "ScreenTapHelper"
    private var instance: ScreenTapHelperImpl? = null

    /**
     * 使用反射创建手势描述
     */
    private fun createGestureDescriptionUsingReflection(path: Path): Any {
        try {
            // 使用反射创建GestureDescription.Builder
            val gestureBuilderClass = Class.forName("android.accessibilityservice.AccessibilityService\$GestureDescription\$Builder")
            val gestureBuilder = gestureBuilderClass.getDeclaredConstructor().newInstance()
            
            // 使用反射创建StrokeDescription.Builder
            val strokeBuilderClass = Class.forName("android.accessibilityservice.AccessibilityService\$GestureDescription\$StrokeDescription\$Builder")
            val strokeBuilder = strokeBuilderClass.getDeclaredConstructor(Path::class.java, Long::class.java, Long::class.java)
                .newInstance(path, 0L, 100L) // 0ms延迟，100ms完成
            
            // 调用build方法创建StrokeDescription
            val buildStrokeMethod = strokeBuilderClass.getMethod("build")
            val strokeDescription = buildStrokeMethod.invoke(strokeBuilder)
            
            // 添加stroke到gestureBuilder
            val addStrokeMethod = gestureBuilderClass.getMethod("addStroke", Class.forName("android.accessibilityservice.AccessibilityService\$GestureDescription\$StrokeDescription"))
            addStrokeMethod.invoke(gestureBuilder, strokeDescription)
            
            // 构建GestureDescription
            val buildGestureMethod = gestureBuilderClass.getMethod("build")
            return buildGestureMethod.invoke(gestureBuilder)
        } catch (e: Exception) {
            Log.e(TAG, "使用反射创建手势描述失败: " + e.message, e)
            throw RuntimeException("无法创建手势描述: " + e.message, e)
        }
    }
    
    /**
     * 屏幕点击方式枚举
     */
    enum class TapMethod {
        /**
         * 自动选择最佳方式
         */
        AUTO,
        
        /**
         * 使用InputManager方式（Android 6.0+）
         */
        INPUT_MANAGER,
        
        /**
         * 使用Instrumentation方式
         */
        INSTRUMENTATION,
        
        /**
         * 使用反射方式
         */
        REFLECTION,
        
        /**
         * 使用Root权限的底层触摸事件
         */
        ROOT,
        
        /**
         * 使用命令行input tap命令
         */
        INPUT_COMMAND,
        
        /**
         * 使用AccessibilityService手势操作（Android 7.0+）
         */
        ACCESSIBILITY_GESTURE
    }

    /**
     * 获取ScreenTapHelper实例
     */
    fun getInstance(context: Context): ScreenTapHelperImpl {
        if (instance == null) {
            synchronized(ScreenTapHelper::class.java) {
                if (instance == null) {
                    instance = ScreenTapHelperImpl(context)
                }
            }
        }
        return instance!!
    }

    /**
     * 内部实现类
     */
    class ScreenTapHelperImpl(private val context: Context) {
        /**
         * 点击屏幕指定坐标位置
         * @param x X坐标
         * @param y Y坐标
         * @param listener 点击回调监听器
         * @param method 点击方式，默认为AUTO
         */
        fun tapScreen(x: Float, y: Float, listener: OnTapListener, method: TapMethod = TapMethod.AUTO) {
            try {
                when (method) {
                    TapMethod.AUTO -> {
                        // 自动选择最佳方式，尝试多种方法直到成功
                        val methodsToTry = mutableListOf<() -> Unit>()
                        
                        // 根据Android版本和服务状态添加尝试顺序
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N && isAccessibilityServiceEnabled()) {
                            // 优先使用无障碍手势
                            methodsToTry.add { tapScreenWithAccessibilityGesture(x, y) }
                        }
                        
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                            // 其次使用InputManager方法
                            methodsToTry.add { tapScreenWithInputManager(x, y) }
                        } else {
                            // Android 6.0以下版本使用Instrumentation方法
                            methodsToTry.add { tapScreenWithInstrumentation(x, y) }
                        }
                        
                        // 添加反射方法作为备选
                        methodsToTry.add { tapScreenWithReflection(x, y) }
                        
                        // Android 8.0+添加命令行方法作为备选
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                            methodsToTry.add { tapScreenWithInputCommand(x, y) }
                        }
                        
                        // 最后尝试Root方式
                        methodsToTry.add { tapScreenWithRootAccess(x, y) }
                        
                        // 依次尝试所有方法直到成功
                        var lastException: Exception? = null
                        for (tapMethod in methodsToTry) {
                            try {
                                tapMethod.invoke()
                                // 如果成功，跳出循环
                                Log.d(TAG, "屏幕点击成功")
                                break
                            } catch (e: Exception) {
                                lastException = e
                                Log.w(TAG, "尝试的点击方法失败: ${e.message}")
                                // 继续尝试下一个方法
                            }
                        }
                        
                        // 如果所有方法都失败，抛出最后一个异常
                        if (lastException != null) {
                            throw lastException
                        }
                    }
                    TapMethod.INPUT_MANAGER -> {
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                            tapScreenWithInputManager(x, y)
                        } else {
                            throw UnsupportedOperationException("InputManager方法仅支持Android 6.0及以上版本")
                        }
                    }
                    TapMethod.INSTRUMENTATION -> {
                        tapScreenWithInstrumentation(x, y)
                    }
                    TapMethod.REFLECTION -> {
                        tapScreenWithReflection(x, y)
                    }
                    TapMethod.ROOT -> {
                        tapScreenWithRootAccess(x, y)
                    }
                    TapMethod.INPUT_COMMAND -> {
                        tapScreenWithInputCommand(x, y)
                    }
                    TapMethod.ACCESSIBILITY_GESTURE -> {
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                            tapScreenWithAccessibilityGesture(x, y)
                        } else {
                            throw UnsupportedOperationException("无障碍手势方法仅支持Android 7.0及以上版本")
                        }
                    }
                }
                listener.onTapSuccess()
            } catch (e: Exception) {
                Log.e(TAG, "点击屏幕失败: ${e.message}", e)
                // 提供更友好的错误信息
                val friendlyMessage = when {
                    e is SecurityException || e.message?.contains("权限") == true -> 
                        "屏幕点击操作需要相应权限。建议启用无障碍服务或授予相关权限。"
                    e is InvocationTargetException -> 
                        "系统安全限制阻止了点击操作。建议启用无障碍服务以获得更好的兼容性。"
                    e is NoSuchMethodException -> 
                        "设备Android版本与点击方法不兼容。建议使用无障碍服务或尝试其他点击方式。"
                    else -> "点击失败: ${e.message}"
                }
                listener.onTapFailure(RuntimeException(friendlyMessage, e))
            }
        }

        /**
         * 检查无障碍服务是否已启用
         * @return true表示已启用，false表示未启用
         */
        private fun isAccessibilityServiceEnabled(): Boolean {
            return try {
                // 同时检查无障碍服务是否已启用并且服务实例可用
                val serviceEnabled = AccessibilityServiceHelper.isEnabled(context)
                val serviceInstanceAvailable = AccessibilityServiceHelper.getInstance() != null
                
                if (serviceEnabled && !serviceInstanceAvailable) {
                    Log.w(TAG, "无障碍服务已在系统设置中启用，但服务实例不可用。这可能是因为服务尚未完全初始化。")
                }
                
                serviceEnabled && serviceInstanceAvailable
            } catch (e: Exception) {
                Log.w(TAG, "无法检查无障碍服务状态", e)
                false
            }
        }

        /**
         * 打开无障碍服务设置界面
         * 在使用ACCESSIBILITY_GESTURE方式前，应该调用此方法引导用户开启无障碍服务
         */
        fun openAccessibilitySettings() {
            AccessibilityServiceHelper.openAccessibilitySettings(context)
        }

        /**
         * 点击屏幕中心点
         * @param listener 点击回调监听器
         * @param method 点击方式，默认为AUTO
         */
        fun tapCenterScreen(listener: OnTapListener, method: TapMethod = TapMethod.AUTO) {
            try {
                val displayMetrics = context.resources.displayMetrics
                val screenWidth = displayMetrics.widthPixels
                val screenHeight = displayMetrics.heightPixels
                
                val centerX = screenWidth / 2f
                val centerY = screenHeight / 2f
                
                tapScreen(centerX, centerY, listener, method)
            } catch (e: Exception) {
                Log.e(TAG, "点击屏幕中心点失败: ${e.message}", e)
                listener.onTapFailure(e)
            }
        }

        /**
         * 点击屏幕相对位置
         * @param relativeX 相对X位置 (0.0-1.0)
         * @param relativeY 相对Y位置 (0.0-1.0)
         * @param listener 点击回调监听器
         * @param method 点击方式，默认为AUTO
         */
        fun tapRelativePosition(relativeX: Float, relativeY: Float, listener: OnTapListener, method: TapMethod = TapMethod.AUTO) {
            try {
                if (relativeX < 0 || relativeX > 1 || relativeY < 0 || relativeY > 1) {
                    throw IllegalArgumentException("相对位置坐标必须在0.0到1.0之间")
                }

                val displayMetrics = context.resources.displayMetrics
                val screenWidth = displayMetrics.widthPixels
                val screenHeight = displayMetrics.heightPixels

                val x = (screenWidth * relativeX).toFloat()
                val y = (screenHeight * relativeY).toFloat()

                tapScreen(x, y, listener, method)
            } catch (e: Exception) {
                Log.e(TAG, "点击相对位置失败: ${e.message}", e)
                listener.onTapFailure(e)
            }
        }

        /**
         * 使用Instrumentation方法点击屏幕
         * 注意：需要在主线程或使用Handler在主线程中执行
         */
        private fun tapScreenWithInstrumentation(x: Float, y: Float) {
            Handler(Looper.getMainLooper()).post {
                try {
                    val instrumentation = Instrumentation()
                    instrumentation.sendPointerSync(MotionEvent.obtain(
                        System.currentTimeMillis(),
                        System.currentTimeMillis() + 10,
                        MotionEvent.ACTION_DOWN,
                        x, y,
                        0
                    ))
                    instrumentation.sendPointerSync(MotionEvent.obtain(
                        System.currentTimeMillis(),
                        System.currentTimeMillis() + 10,
                        MotionEvent.ACTION_UP,
                        x, y,
                        0
                    ))
                } catch (e: SecurityException) {
                    Log.e(TAG, "需要ACCESS_MOCK_LOCATION权限", e)
                    // 在没有权限的情况下使用备用方法
                    tapScreenWithReflection(x, y)
                }
            }
        }

        /**
         * 使用InputManager方法点击屏幕
         * Android 6.0及以上版本可用
         */
        @RequiresApi(Build.VERSION_CODES.M)
        private fun tapScreenWithInputManager(x: Float, y: Float) {
            try {
                // 获取InputManager的实例
                val inputManagerClass = Class.forName("android.hardware.input.InputManager")
                val getInstanceMethod = inputManagerClass.getMethod("getInstance")
                val inputManager = getInstanceMethod.invoke(null)

                // 创建MotionEvent
                val downTime = System.currentTimeMillis()
                val eventTime = System.currentTimeMillis() + 10
                
                // 构建ACTION_DOWN事件
                val downEvent = MotionEvent.obtain(
                    downTime,
                    eventTime,
                    MotionEvent.ACTION_DOWN,
                    x,
                    y,
                    0
                )
                downEvent.source = InputDevice.SOURCE_TOUCHSCREEN

                // 构建ACTION_UP事件
                val upEvent = MotionEvent.obtain(
                    downTime,
                    eventTime + 10,
                    MotionEvent.ACTION_UP,
                    x,
                    y,
                    0
                )
                upEvent.source = InputDevice.SOURCE_TOUCHSCREEN

                // 调用injectInputEvent方法 - 使用InputEvent作为参数类型以避免NoSuchMethodException
                val injectInputEventMethod = inputManagerClass.getMethod(
                    "injectInputEvent",
                    android.view.InputEvent::class.java,
                    Int::class.javaPrimitiveType
                )
                
                // 在较新的Android版本中，这个方法可能需要特定权限，尝试调用并捕获可能的异常
                try {
                    injectInputEventMethod.invoke(inputManager, downEvent, 0)
                    injectInputEventMethod.invoke(inputManager, upEvent, 0)
                } catch (targetException: java.lang.reflect.InvocationTargetException) {
                    // 捕获InvocationTargetException，这通常是因为权限不足
                    Log.e(TAG, "使用InputManager方法点击失败，可能是权限不足: ${targetException.targetException}", targetException)
                    
                    // 尝试不同的参数组合
                    try {
                        Log.d(TAG, "尝试使用不同的参数组合调用injectInputEvent")
                        // 尝试使用不同的flag值
                        val injectFlags = arrayOf(0, 1, 2)
                        for (flag in injectFlags) {
                            try {
                                injectInputEventMethod.invoke(inputManager, downEvent, flag)
                                injectInputEventMethod.invoke(inputManager, upEvent, flag)
                                Log.d(TAG, "使用flag=" + flag + "成功调用injectInputEvent")
                                return // 成功了就返回
                            } catch (e: Exception) {
                                // 继续尝试下一个flag
                                Log.d(TAG, "使用flag=" + flag + "调用injectInputEvent失败: " + e.message)
                            }
                        }
                        // 所有flag都尝试失败，抛出原始异常
                        throw targetException
                    } catch (e: Exception) {
                        // 二次尝试也失败，抛出原始异常
                        throw targetException
                    }
                }

                // 回收事件
                downEvent.recycle()
                upEvent.recycle()
            } catch (e: Exception) {
                Log.e(TAG, "使用InputManager方法点击失败", e)
                // 降级到反射方法
                tapScreenWithReflection(x, y)
            }
        }

        /**
         * 使用反射方式点击屏幕
         * 作为备用方案
         */
        private fun tapScreenWithReflection(x: Float, y: Float) {
            try {
                val windowManager = context.getSystemService(Context.WINDOW_SERVICE) as WindowManager
                val size = Point()
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
                    // Android 11+ 使用新API
                    val metrics = windowManager.currentWindowMetrics
                    size.x = metrics.bounds.width()
                    size.y = metrics.bounds.height()
                } else {
                    // 旧版本使用已弃用的API
                    val display: Display = windowManager.defaultDisplay
                    display.getSize(size)
                }

                // 使用反射调用MotionEvent的方法
                val motionEventClass = Class.forName("android.view.MotionEvent")
                
                // 尝试找到合适的obtain方法（适应不同Android版本的参数变化）
                val obtainMethod = try {
                    // 尝试标准的obtain方法（参数较少的版本）
                    motionEventClass.getMethod(
                        "obtain",
                        Long::class.javaPrimitiveType,
                        Long::class.javaPrimitiveType,
                        Int::class.javaPrimitiveType,
                        Float::class.javaPrimitiveType,
                        Float::class.javaPrimitiveType,
                        Int::class.javaPrimitiveType
                    )
                } catch (e1: NoSuchMethodException) {
                    try {
                        // 尝试完整参数版本的obtain方法
                        motionEventClass.getMethod(
                            "obtain",
                            Long::class.javaPrimitiveType,
                            Long::class.javaPrimitiveType,
                            Int::class.javaPrimitiveType,
                            Float::class.javaPrimitiveType,
                            Float::class.javaPrimitiveType,
                            Float::class.javaPrimitiveType,
                            Float::class.javaPrimitiveType,
                            Int::class.javaPrimitiveType,
                            Int::class.javaPrimitiveType,
                            Int::class.javaPrimitiveType,
                            Int::class.javaPrimitiveType,
                            Int::class.javaPrimitiveType
                        )
                    } catch (e2: NoSuchMethodException) {
                        // 尝试其他可能的obtain方法签名
                        try {
                            motionEventClass.getMethod(
                                "obtain",
                                Long::class.javaPrimitiveType,
                                Long::class.javaPrimitiveType,
                                Int::class.javaPrimitiveType,
                                Float::class.javaPrimitiveType,
                                Float::class.javaPrimitiveType
                            )
                        } catch (e3: NoSuchMethodException) {
                            // 所有尝试都失败，抛出原始异常
                            throw e3
                        }
                    }
                }

                // 根据obtainMethod的参数数量创建事件
                val downEvent = try {
                    when (obtainMethod.parameterTypes.size) {
                        5 -> {
                            // 最简单的版本: downTime, eventTime, action, x, y
                            obtainMethod.invoke(
                                null,
                                System.currentTimeMillis(),
                                System.currentTimeMillis() + 10,
                                MotionEvent.ACTION_DOWN,
                                x,
                                y
                            ) as MotionEvent
                        }
                        6 -> {
                            // 标准版本: downTime, eventTime, action, x, y, metaState
                            obtainMethod.invoke(
                                null,
                                System.currentTimeMillis(),
                                System.currentTimeMillis() + 10,
                                MotionEvent.ACTION_DOWN,
                                x,
                                y,
                                0 // metaState
                            ) as MotionEvent
                        }
                        12 -> {
                            // 完整版本
                            obtainMethod.invoke(
                                null,
                                System.currentTimeMillis(),
                                System.currentTimeMillis() + 10,
                                MotionEvent.ACTION_DOWN,
                                x,
                                y,
                                0f,
                                0f,
                                0,
                                0,
                                0,
                                0,
                                0
                            ) as MotionEvent
                        }
                        else -> {
                            // 未知版本，尝试使用反射创建实例
                            val constructor = motionEventClass.getDeclaredConstructor()
                            constructor.isAccessible = true
                            val event = constructor.newInstance() as MotionEvent
                            
                            // 使用其他方法设置属性
                            val setActionMethod = motionEventClass.getMethod("setAction", Int::class.javaPrimitiveType)
                            val setLocationMethod = motionEventClass.getMethod("setLocation", Float::class.javaPrimitiveType, Float::class.javaPrimitiveType)
                            setActionMethod.invoke(event, MotionEvent.ACTION_DOWN)
                            setLocationMethod.invoke(event, x, y)
                            event
                        }
                    }
                } catch (e: Exception) {
                    Log.e(TAG, "创建MotionEvent失败: ${e.message}", e)
                    throw e
                }

                // 创建ACTION_UP事件（使用相同的逻辑）
                val upEvent = try {
                    when (obtainMethod.parameterTypes.size) {
                        5 -> {
                            obtainMethod.invoke(
                                null,
                                System.currentTimeMillis(),
                                System.currentTimeMillis() + 20,
                                MotionEvent.ACTION_UP,
                                x,
                                y
                            ) as MotionEvent
                        }
                        6 -> {
                            obtainMethod.invoke(
                                null,
                                System.currentTimeMillis(),
                                System.currentTimeMillis() + 20,
                                MotionEvent.ACTION_UP,
                                x,
                                y,
                                0 // metaState
                            ) as MotionEvent
                        }
                        12 -> {
                            obtainMethod.invoke(
                                null,
                                System.currentTimeMillis(),
                                System.currentTimeMillis() + 20,
                                MotionEvent.ACTION_UP,
                                x,
                                y,
                                0f,
                                0f,
                                0,
                                0,
                                0,
                                0,
                                0
                            ) as MotionEvent
                        }
                        else -> {
                            val constructor = motionEventClass.getDeclaredConstructor()
                            constructor.isAccessible = true
                            val event = constructor.newInstance() as MotionEvent
                            
                            val setActionMethod = motionEventClass.getMethod("setAction", Int::class.javaPrimitiveType)
                            val setLocationMethod = motionEventClass.getMethod("setLocation", Float::class.javaPrimitiveType, Float::class.javaPrimitiveType)
                            setActionMethod.invoke(event, MotionEvent.ACTION_UP)
                            setLocationMethod.invoke(event, x, y)
                            event
                        }
                    }
                } catch (e: Exception) {
                        // 如果创建失败，先回收downEvent
                        if (downEvent != null) {
                            try {
                                downEvent.recycle()
                            } catch (recycleE: Exception) {
                                // 回收失败时忽略
                            }
                        }
                    Log.e(TAG, "创建MotionEvent失败: ${e.message}", e)
                    throw e
                }

                // 获取WindowManager的实例并注入事件
                val windowManagerGlobalClass = Class.forName("android.view.WindowManagerGlobal")
                val getInstanceMethod = windowManagerGlobalClass.getMethod("getInstance")
                val windowManagerGlobal = getInstanceMethod.invoke(null)
                val injectInputEventMethod = windowManagerGlobalClass.getMethod(
                    "injectInputEvent",
                    MotionEvent::class.java,
                    Int::class.javaPrimitiveType
                )

                try {
                    injectInputEventMethod.invoke(windowManagerGlobal, downEvent, 0)
                    injectInputEventMethod.invoke(windowManagerGlobal, upEvent, 0)
                } catch (targetException: java.lang.reflect.InvocationTargetException) {
                    // 捕获InvocationTargetException，这通常是因为权限不足
                    Log.e(TAG, "使用WindowManagerGlobal注入事件失败，可能是权限不足: ${targetException.targetException}", targetException)
                    
                    // 尝试使用InputCommand方法作为最后的备选
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                        try {
                            Log.d(TAG, "尝试使用命令行方式点击屏幕")
                            tapScreenWithInputCommand(x, y)
                            return
                        } catch (cmdException: Exception) {
                            Log.e(TAG, "使用命令行方式点击也失败", cmdException)
                        }
                    }
                    
                    throw targetException
                }

                // 回收事件
                downEvent.recycle()
                upEvent.recycle()
            } catch (e: Exception) {
                Log.e(TAG, "使用反射方法点击失败", e)
                
                // 如果所有方法都失败，提供更友好的错误信息
                val errorMessage = "无法执行屏幕点击操作。这通常是因为Android系统的安全限制。\n" +
                        "建议启用无障碍服务，这是最可靠的屏幕点击方式。"
                throw RuntimeException(errorMessage, e)
            }
        }

        /**
         * 使用Root权限的底层触摸事件发送
         * @param x X坐标
         * @param y Y坐标
         */
        private fun tapScreenWithRootAccess(x: Float, y: Float) {
            try {
                // 执行su命令获取Root权限
                val process = Runtime.getRuntime().exec("su")
                val outputStream = process.outputStream
                
                // 获取触摸设备路径
                val touchDevicePath = getTouchDevicePath()
                
                if (touchDevicePath.isNotEmpty()) {
                    // 构造sendevent命令
                    val xInt = x.toInt()
                    val yInt = y.toInt()
                    
                    // 发送触摸事件
                    val commands = """
echo "sendevent $touchDevicePath 3 53 $xInt" > /proc/self/fd/1
echo "sendevent $touchDevicePath 3 54 $yInt" > /proc/self/fd/1
echo "sendevent $touchDevicePath 3 58 50" > /proc/self/fd/1
echo "sendevent $touchDevicePath 0 0 0" > /proc/self/fd/1
sleep 0.05
echo "sendevent $touchDevicePath 3 58 0" > /proc/self/fd/1
echo "sendevent $touchDevicePath 0 0 0" > /proc/self/fd/1
""".trimIndent()
                    
                    outputStream.write(commands.toByteArray())
                    outputStream.flush()
                    outputStream.close()
                    
                    // 等待命令执行完成
                    process.waitFor()
                } else {
                    throw UnsupportedOperationException("未找到触摸设备路径")
                }
            } catch (e: Exception) {
                Log.e(TAG, "使用Root权限点击失败", e)
                throw RuntimeException("Root权限不足或操作失败", e)
            }
        }

        /**
         * 获取触摸设备路径
         * @return 触摸设备路径
         */
        private fun getTouchDevicePath(): String {
            try {
                // 执行getevent命令获取输入设备信息
                val process = Runtime.getRuntime().exec(arrayOf("sh", "-c", "getevent -lp | grep -B 15 ABS_MT_POSITION_X | head -1"))
                val inputStream = process.inputStream
                val reader = java.io.BufferedReader(java.io.InputStreamReader(inputStream))
                val line = reader.readLine()
                reader.close()
                
                if (line != null && line.startsWith("add device ")) {
                    return line.substring("add device ".length)
                }
            } catch (e: Exception) {
                Log.e(TAG, "获取触摸设备路径失败", e)
            }
            
            // 返回常见的触摸设备路径作为备选
            return "/dev/input/event0"
        }

        /**
         * 使用命令行input tap命令
         * @param x X坐标
         * @param y Y坐标
         */
        private fun tapScreenWithInputCommand(x: Float, y: Float) {
            try {
                // 执行input tap命令
                val process = Runtime.getRuntime().exec(arrayOf("input", "tap", x.toString(), y.toString()))
                
                // 等待命令执行完成
                val exitCode = process.waitFor()
                
                if (exitCode != 0) {
                    throw RuntimeException("input tap命令执行失败，退出码: $exitCode")
                }
            } catch (e: Exception) {
                Log.e(TAG, "使用input tap命令点击失败", e)
                throw RuntimeException("无足够权限执行input tap命令", e)
            }
        }

        /**
         * 使用AccessibilityService手势操作
         * Android 7.0及以上版本可用
         * @param x X坐标
         * @param y Y坐标
         */
        /**
         * 使用无障碍服务发送手势点击屏幕
         * @param x X坐标
         * @param y Y坐标
         */
        @RequiresApi(Build.VERSION_CODES.N)
        private fun tapScreenWithAccessibilityGesture(x: Float, y: Float) {
            try {
                // 改进：添加多次尝试获取无障碍服务实例的逻辑
                var accessibilityService: Any? = null
                val maxInstanceRetries = 3
                var instanceRetryCount = 0
                
                while (accessibilityService == null && instanceRetryCount < maxInstanceRetries) {
                    // 使用反射获取无障碍服务实例
                    val getInstanceMethod = AccessibilityServiceHelper::class.java.getDeclaredMethod("getInstance")
                    getInstanceMethod.isAccessible = true
                    accessibilityService = getInstanceMethod.invoke(null)
                    
                    if (accessibilityService == null) {
                        instanceRetryCount++
                        if (instanceRetryCount < maxInstanceRetries) {
                            Log.d(TAG, "尝试重新获取无障碍服务实例，次数: $instanceRetryCount")
                            Thread.sleep(200)
                        }
                    }
                }
                
                if (accessibilityService == null) {
                    // 检查系统设置中是否启用了无障碍服务
                    val isEnabledMethod = AccessibilityServiceHelper::class.java.getDeclaredMethod("isEnabled", Context::class.java)
                    isEnabledMethod.isAccessible = true
                    val isSystemEnabled = isEnabledMethod.invoke(null, context) as Boolean
                    
                    val errorMessage = if (isSystemEnabled) {
                        "无障碍服务已在系统设置中启用，但无法获取有效的服务实例。这可能是因为：\n" +
                        "1. 服务尚未完全初始化\n" +
                        "2. 应用进程被系统回收\n" +
                        "3. 无障碍服务配置问题\n" +
                        "建议：尝试重新启用无障碍服务或重启应用。"
                    } else {
                        "无法获取有效的AccessibilityService实例。请在系统设置中启用无障碍服务。"
                    }
                    
                    throw RuntimeException(errorMessage)
                }
                
                // 确保坐标非负
                val startX = Math.max(0f, x)
                val startY = Math.max(0f, y)
                
                // 创建手势路径 - 改进：增加一个小的移动路径，使点击更可靠
                val path = Path()
                path.moveTo(startX, startY)
                // 添加一个非常小的偏移，确保手势被系统识别为有效点击
                path.lineTo(startX + 1f, startY + 1f)
                
                // 最多尝试3次
                val maxRetries = 3
                var currentRetry = 0
                var success = false
                
                while (currentRetry <= maxRetries && !success) {
                    if (currentRetry > 0) {
                        Log.d(TAG, "重试无障碍手势，次数: " + currentRetry)
                        // 重试之间添加短暂延迟
                        Thread.sleep(200)
                    }
                    
                    // 使用同步方式等待手势执行结果
                    val latch = java.util.concurrent.CountDownLatch(1)
                    var gestureSuccess = false
                    
                    // 再次检查服务实例是否有效
                    val getInstanceMethod = AccessibilityServiceHelper::class.java.getDeclaredMethod("getInstance")
                    getInstanceMethod.isAccessible = true
                    if (getInstanceMethod.invoke(null) == null) {
                        Log.e(TAG, "无障碍服务实例已失效，尝试重新获取")
                        accessibilityService = getInstanceMethod.invoke(null)
                        if (accessibilityService == null) {
                            throw RuntimeException("无障碍服务实例已失效且无法重新获取")
                        }
                    }
                    
                    try {
                        // 使用完整的反射方式创建手势描述
                        val gestureDescription = createGestureDescriptionUsingReflection(path)
                        
                        // 使用反射调用dispatchGesture方法
                        val dispatchGestureMethod = accessibilityService!!.javaClass.getMethod(
                            "dispatchGesture",
                            Any::class.java,  // GestureDescription
                            Any::class.java,  // GestureResultCallback
                            Handler::class.java
                        )
                        
                        // 创建手势回调
                        val callbackClass = Class.forName("android.accessibilityservice.AccessibilityService\$GestureResultCallback")
                        val callback = Proxy.newProxyInstance(
                            callbackClass.classLoader,
                            arrayOf(callbackClass),
                            InvocationHandler { proxy, method, args ->
                                if (method.name == "onCompleted") {
                                    Log.d(TAG, "无障碍手势点击完成")
                                    gestureSuccess = true
                                    latch.countDown()
                                } else if (method.name == "onCancelled") {
                                    Log.e(TAG, "无障碍手势点击被取消")
                                    latch.countDown()
                                }
                                null
                            }
                        )
                        
                        // 调用dispatchGesture方法
                        val dispatchSuccess = dispatchGestureMethod.invoke(
                            accessibilityService,
                            gestureDescription,
                            callback,
                            Handler(Looper.getMainLooper())
                        ) as Boolean?
                        
                        if (dispatchSuccess != true) {
                            Log.e(TAG, "发送无障碍手势失败，准备重试")
                            currentRetry++
                            continue
                        }
                        
                        // 等待手势执行完成或超时 - 增加超时时间到3秒
                        latch.await(3000, java.util.concurrent.TimeUnit.MILLISECONDS)
                        
                        if (gestureSuccess) {
                            success = true
                        } else {
                            Log.e(TAG, "无障碍手势执行超时，准备重试")
                            currentRetry++
                        }
                    } catch (e: Exception) {
                        Log.e(TAG, "反射执行无障碍手势失败: " + e.message, e)
                        currentRetry++
                    }
                }
                
                if (!success) {
                    throw RuntimeException("无障碍手势执行失败，已尝试 " + (maxRetries + 1) + " 次")
                }
                
                // 短暂延迟确保手势有时间执行
                Thread.sleep(150)
            } catch (e: Exception) {
                Log.e(TAG, "使用无障碍手势点击失败", e)
                
                // 如果无障碍手势失败，降级到InputManager方法
                Log.d(TAG, "无障碍手势失败，降级到InputManager方法")
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    tapScreenWithInputManager(x, y)
                } else {
                    // 如果Android版本低于6.0，降级到Instrumentation方法
                    tapScreenWithInstrumentation(x, y)
                }
            }
        }

        /**
         * 获取屏幕尺寸
         * @return 包含屏幕宽度和高度的Point对象
         */
        fun getScreenSize(): Point {
            val windowManager = context.getSystemService(Context.WINDOW_SERVICE) as WindowManager
            val size = Point()
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
                // Android 11+ 使用新API
                val metrics = windowManager.currentWindowMetrics
                size.x = metrics.bounds.width()
                size.y = metrics.bounds.height()
            } else {
                // 旧版本使用已弃用的API
                val display: Display = windowManager.defaultDisplay
                display.getSize(size)
            }
            return size
        }
    }

    /**
     * 点击回调接口
     */
    interface OnTapListener {
        /**
         * 点击成功回调
         */
        fun onTapSuccess()

        /**
         * 点击失败回调
         * @param exception 失败异常
         */
        fun onTapFailure(exception: Exception)
    }
}